package com.zyf.controller;

import com.zyf.pojo.Role;
import com.zyf.pojo.Users;
import com.zyf.service.RoleService;
import com.zyf.service.UsersService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UsersController {

    @Resource
    UsersService service;

    @Resource
    RoleService roleservice;


    @GetMapping({"/","index"})
    public String index(){
        return "../index";
    }

    @GetMapping("/user/findAll")
    public String findAll(Model model){
        List<Users> all = service.findAll();
        model.addAttribute("users",all);
        return "userList";
    }

    @GetMapping("/user/delete")
    public String delete(Integer uid,Model model){
        int i = service.delete(uid);
        if (i<=0){
            model.addAttribute("message","添加失败");
            return "userList";
        }
        return "redirect:/user/findAll";
    }

    @GetMapping("/user/findOne")
    public String findOne(Integer uid,Model model){
        Users one = service.findOne(uid);
        model.addAttribute("user",one);
        List<Role> roleList = roleservice.findAll();
        model.addAttribute("roles",roleList);
        return "userUpdate";
    }
    @GetMapping("/user/toAdd")
    public String toAdd(Model model){
        List<Role> roleList = roleservice.findAll();
        model.addAttribute("roles",roleList);
        return "userAdd";
    }

    @PostMapping("/user/add")
    public String add(Users user,Model model){
        int i = service.add(user);
        if (i<=0){
            model.addAttribute("message","添加失败");
            return "userAdd";
        }
        return "redirect:/user/findAll";
    }

    @PostMapping("/user/update")
    public String update(Users users,Model model){
        int i = service.update(users);
        if (i<=0){
            model.addAttribute("message","修改失败");
            return "userUpdate";
        }
        return "redirect:/user/findAll";
    }
}
